class Repertuar < CachedModel
  set_table_name 'repertuar'
  set_primary_key 'ID_repertuar'
  belongs_to :film,
    :class_name => "Film" ,
    :foreign_key => "ID_film"
  belongs_to :kino,
    :class_name => "Kino" ,
    :foreign_key => "ID_kino"

  include PageThief    
  include KinaMap
  include DatesHelper
  
  include ActionView::Helpers::PrototypeHelper
    
#  def save
#     self.evnt_id = 0
#     super
#  end
  
  def self.read_barany date = nil
    url = 'http://www.kinopodbaranami.pl/repertuar.php'
    encoding = "iso-8859-2"    
    titles, dates, hours, ids = [], [], [], []
    doc = PageThief.get_page_dom(url, encoding)
    node = doc.get_elements('//table[@class="ruler"]')[0]
    date = ''
    node.elements.each('descendant::tr') do |tr_node|
      th_node = tr_node.get_elements('descendant::th')[0]
      unless th_node.nil?
        if date.blank?
          year = Time.new.strftime('%Y')
          date_full = th_node.text.strip
          day = date_full[date_full.index(' ')+1...date_full.rindex(' ')]        
          month_txt = date_full[date_full.rindex(' ')+1...date_full.length].downcase
          month = DatesHelper.get_en_month_name month_txt
          date = Time.parse(day + "-" + month + "-" + year)
        else
          new_date = date + 1.day
          date = (new_date.strftime("%Y-%m-%d") == date.strftime("%Y-%m-%d") ? new_date + 1.day : new_date)
        end        
      else
        film_node = tr_node.get_elements('descendant::a[@title]')[0]
        titles << Iconv.new(WIN, UTF).iconv(film_node.text.strip)
        href = film_node.attribute('href').value
        ids << href[href.rindex('=')+1...href.length]
        dates << date.strftime("%Y-%m-%d")
        hour_node = tr_node.get_elements('descendant::td[@align="center"]')[0]
        hour = hour_node.text.strip+":00"
        hours << hour
      end
    end
    [ titles, dates, hours, ids]   
  end  
  
  def self.read_sfinks date = nil
    url = 'http://www.kinosfinks.pl/index.php?option=com_content&task=blogcategory&id=32'
    encoding = "iso-8859-2"    
    titles, dates, hours, ids = [], [], [], []
    doc = PageThief.get_page_dom(url, encoding)
    node = doc.get_elements('//table[@width="540"]')[0]
    node.elements.each('descendant::tr') do |tr_node|
        date_node = tr_node.get_elements('descendant::td')[0]
        year = Time.new.strftime('%Y')
        date_full = date_node.text.gsub('&nbsp;',' ').strip
        begin        
        day = date_full[0..date_full.index(' ')].strip
        month_txt = date_full[date_full.rindex(' ')+1..date_full.length]
        month = DatesHelper.get_en_month_name_from_rom(month_txt) 

          date = Time.parse(day + "-" + month + "-" + year)
        rescue
          raise date_full + ": (#{month_txt}-#{day})" + (day.to_s + "-" + month.to_s + "-" + year.to_s)
        end
        hour_node = tr_node.get_elements('descendant::td')[2]
        hours_arr = hour_node.texts.map{ |x| x.value.gsub('.', ':').gsub('&nbsp;','').strip+':00' }
        tyt_td_node = tr_node.get_elements('descendant::td')[3]
        i = 0
        if tyt_td_node.get_elements('descendant::a').empty?
          tyt_td_node.texts.each { |tyt|
            titles << Iconv.new(WIN, UTF).iconv(tyt.value) 
            dates << date.strftime("%Y-%m-%d")
            ids << ''
            hours << hours_arr[i]
            i += 1          
          }          
        else
          tyt_td_node.elements.each('descendant::a') { |tyt_node|
            unless tyt_node.texts.nil?
              titles << Iconv.new(WIN, UTF).iconv(tyt_node.text) 
              dates << date.strftime("%Y-%m-%d")
              href = tyt_node.attribute('href').value
              ids << href[href.rindex('=')+1...href.length]
              hours << hours_arr[i]
            end
            i += 1          
          }
        end
    end
    [ titles, dates, hours, ids]
  end
  
  def self.read_ars date = nil
    url = 'http://www.dokina.pl/dokina.php?kino=2'
    encoding = "iso-8859-2"    
    titles, dates, hours, obce_id, cine = [], [], [], [], []
    doc = PageThief.get_page_dom(url, encoding)

    day_counter = 0
    doc.elements.each('//tr[@bgcolor="#C4D3DB"]') do |node|
      if day_counter == 0
        year = Time.new.strftime('%Y')
        date_full = node.get_elements('th')[0].text
        day = date_full[date_full.index('&nbsp; ')+7...date_full.rindex(' ')]        
        month_txt = date_full[date_full.rindex(' ')+1...date_full.length]
        month = DatesHelper.get_en_month_name Iconv.new(ISO, UTF).iconv(month_txt)
        date = Time.parse(day + "-" + month + "-" + year)
      else
        new_date = date + 1.day
        date = (new_date.strftime("%Y-%m-%d") == date.strftime("%Y-%m-%d") ? new_date + 1.day : new_date)
      end
      
      while node.next_element.attribute('bgcolor').value == '#EFEFEF' || node.next_element.attribute('bgcolor').value == '#F5F5F5'
          node = node.next_element
          img_node = node.get_elements('descendant::img')[0]
          dates << date.strftime("%Y-%m-%d")
          cine << img_node.attribute('src').value

          tyt_node = node.get_elements('descendant::a[@class="film2"]')[0]
          titles << Iconv.new(WIN, UTF).iconv(tyt_node.text)
          ob_id = tyt_node.attribute('href').value
          obce_id << ob_id[ob_id.index('?nr=')+4...ob_id.length]
          godz_node = node.get_elements('descendant::a[@onmouseout]')[0] || node.get_elements('descendant::strike')[0]
          hours << godz_node.text+':00'
          break if node.next_element.nil? || node.next_element.attribute('bgcolor').nil?
      end
      day_counter += 1
    end  
    [titles, dates, hours, obce_id, cine]
  end
  
  def self.read_cc date = nil
    encoding = "iso-8859-2"
    titles, titles_orig, hours, cine, obce_id = [], [], [], [], []  
    @@kina_map.each do |name, kino_id|
      if name.to_s.starts_with?('cc')
        kino_obce = case kino_id
            when @@kina_map[:cc_kazimierz]
              1076
            when @@kina_map[:cc_plaza]
              1063
            when @@kina_map[:cc_zakopianka]
              1064
        end
        url = "http://www.cinema-city.pl/repertuar.php?dd=#{date}&cid=#{kino_obce.to_s}"
        doc = PageThief.get_page_dom(url, encoding)
        
        doc.elements.each('//td[@class="repfilm"]') do |node|
          a_node = node.elements.to_a('descendant::a')[0]
          next if a_node.nil?
          titles << Iconv.new(WIN, UTF).iconv(a_node.text)
          ob_id = a_node.attribute("href").value
          obce_id << ob_id[ob_id.index('fid=')+4...ob_id.length]
          img_node = node.elements.to_a('descendant::img[@src="i/imaxico.gif"]')[0]
          cine << (img_node.nil? ? kino_id : @@kina_map[:imax])
          orig_tit_elem = node.elements.to_a('descendant::h4')[0]
          begin
            titles_orig << (orig_tit_elem.nil? ? '' : Iconv.new(WIN, UTF).iconv(orig_tit_elem.text))
          rescue
            titles_orig << ''
          end
          godziny = []
                       # td -> text_node -> td
          node.next_sibling.next_sibling.elements.each('descendant::span[@class="repgodzinyact" or @class="repgodziny"]') { |godz_node|
            godziny << (godz_node.has_text? ? godz_node.texts[0].value : godz_node.get_elements('descendant::strike')[0].texts[0].value)
          }
          hours << godziny
        end  
      end
    end
    [titles, titles_orig, hours, cine, obce_id]
  end
  
  def self.get_kijow_title(title)
    if title.include?("- KINO CYFROWE")
      title[0...title.index("- KINO CYFROWE")]
    else
      title
    end
  end
   
  def self.read_kijow date = nil
    url = 'http://www.kijow.pl/filmy.php?d=li_daty'
    encoding = "iso-8859-2"    
    doc = PageThief.get_page_dom(url, encoding)
    titles, dates, hours, cine, obce_id = [], [], [], [], []
    rep_table_node = doc.get_elements('//table[@class="tekst_kijow"]')[0]

    rep_table_node.elements.each('descendant::tr') do |node|
      date_node = node.get_elements('descendant::font[@class="tekst_kijow_naglowek2"]')
      unless date_node.empty?
        year = Time.new.strftime('%Y')
        date_full = date_node[0].text
        day = date_full[date_full.index('-')+2...date_full.rindex(' ')]        
        month_txt = date_full[date_full.rindex(' ')+1...date_full.length]
        month = DatesHelper.get_en_month_name(Iconv.new(ISO, UTF).iconv(month_txt).downcase)
        new_date = Time.parse("#{day}-#{month}-#{year}")        
        if date.nil? || new_date > date
          date = new_date
        else
          date = Time.parse("#{day}-#{month}-#{year.to_i+1}")
        end
        next  
      end

      unless node.get_elements('descendant::a').empty?
        tds = node.get_elements('descendant::td')
        t_node = tds[0].get_elements('descendant::font')[0]
        titles << Iconv.new(WIN, UTF).iconv(self.get_kijow_title(t_node.text))
        id_full = tds[0].get_elements('descendant::a')[0].attribute("href").value
        obce_id << id_full[id_full.index("idw=")+4...id_full.index("&okres")]
        cine << Iconv.new(WIN, UTF).iconv(tds[1].text)
        hours << tds[2].text
        dates << date.strftime("%Y-%m-%d")
      end
    end
    
    [titles, dates, hours, cine, obce_id]
  end
  
  def self.read_mikro date = nil
    
    url = 'http://www.kinomikro.pl/filmy.php?d=li&okres=3&data=' + date
    encoding = "iso-8859-2"    
    doc = PageThief.get_page_dom(url, encoding)
    titles, titles_orig, hours, cine, obce_id = [], [], [], [], []
    
    doc.elements.each('//div[@style="text-align:justify; margin-top:4px; margin-left:8px; margin-right:8px; margin-bottom:4px;"]') do |node|
        film_node = node.parent.parent.previous_sibling.previous_sibling.previous_sibling.previous_sibling # tr z tytulem

        title_node = film_node.elements.to_a('descendant::a[@class="linkBlue"]')[0]
        title = Iconv.new(WIN, UTF).iconv(title_node.text) 

        data_node = node.parent.parent # tr z godzina,sala i id filmu
        
        id_node = data_node.elements.to_a('descendant::a[@class="link4"]')[0]
        ob_id = id_node.attribute("href").value
        obce_id_val = ob_id[ob_id.index('idw=')+4...ob_id.length]
        
        data_node.elements.each('descendant::font[@class="tekst_maly_zolty"]') do |node|
            hours << Iconv.new(WIN, UTF).iconv(node.text) if node.text.length > 0 && (node.text =~ /\d/) == 0
            titles << title
            titles_orig << ""            
            obce_id << obce_id_val
        end   
        
        data_node.elements.each('descendant::font[@class="tekst_kijow"]') do |node|
            kino = Iconv.new(WIN, UTF).iconv(node.texts.join)
            if kino.include?('Sala')
                kino = kino[kino.index('Sala')...kino.length] 
                kina = kino.split('&nbsp;')
                cine += kina
            else
              cine << nil
            end
        end  
        
    end
    [titles, titles_orig, hours, obce_id]    

  end

  def self.read_mkino date = nil
    url = self.mkino_get_url_for_date(date)
    encoding = "iso-8859-2"    
    titles, orig_titles, hours, obce_ids = [], [], [], [], []
    
    doc = PageThief.get_page_dom(url, encoding)      
    node = doc.get_elements('//div[@class="contentOpis"]')[0]
 
    node = node.next_element
    while node.attribute('class').value.starts_with?('contentItem') do
      tyt_node = node.get_elements('descendant::div[@class="tytul"]')[0]
      obce_id_node_text = tyt_node.get_elements('descendant::a')[0].attribute('href').value
      obce_ids << obce_id_node_text[obce_id_node_text.rindex(',')+1...obce_id_node_text.rindex('.')]
      tyt = tyt_node.get_elements('descendant::strong')[0].text
      titles << Iconv.new(WIN+'//IGNORE', UTF).iconv(tyt)
      tyt_orig_node = tyt_node.get_elements('descendant::span[@class="small"]')
      orig_titles << ( tyt_orig_node.blank? ? '' : Iconv.new(WIN+'//IGNORE', UTF).iconv(tyt_orig_node[0].text))
      hour_nodes = node.get_elements('descendant::div[@class="godziny"]')[0]
      hour = []
      hour_nodes.get_elements('descendant::a').each { |a_node|
        hour << a_node.text
      }
      hours << hour
      node = node.next_element
    end
    
    [titles, orig_titles, hours, obce_ids]
  end

  def self.mkino_get_url_for_date(date)
    today = Date.today
    url = "http://www.multikino.pl/krakow/repertuar"
   
    case date.to_date
    when today
      url << ".html"
    when today + 1
      url << ",jutro.html"
    else
      for i in 2..13 do
        if date.to_date == today+i
          url << ",nastepnedni,#{i-1}.html" 
          break
        end
      end
    end
    return url
  end
  
  def self.add_rep_for_cc dates
      input_date = dates.kind_of?(Array) ? dates : [dates]
      reps = []
      for date in input_date
        page_data = self.read_cc date
        for i in 0...page_data[0].length do
            tytul = page_data[0][i]
            tytul_oryg = page_data[1][i]
            obce_id = page_data[4][i]
            kino = Kino.find(page_data[3][i])
            godziny = page_data[2][i]
            for godzina in godziny
              reps.concat self.save_rep(obce_id, kino.ID_kino, tytul, tytul_oryg, date, godzina+':00')
            end
        end
      end
      reps
  end

  def self.add_rep_for_mkino dates
      input_date = dates.kind_of?(Array) ? dates : [dates]
      reps = []
      for date in input_date
        page_data = self.read_mkino(date)
        for i in 0...page_data[0].length do
            tytul = page_data[0][i]
            tytul_oryg = page_data[1][i]
            godziny = page_data[2][i]
            obce_id = page_data[3][i]
            kino = Kino.find(@@kina_map[:mkino])
            for godzina in godziny
              reps.concat self.save_rep(obce_id, kino.ID_kino, tytul, tytul_oryg, date, godzina+':00')
            end
        end
      end
      reps
  end

  def self.add_rep_for_barany dates
      input_date = dates.kind_of?(Array) ? dates : [dates]
      reps = []
      page_data = self.read_barany
#      raise page_data.inspect
      for i in 0...page_data[0].length do
          next unless input_date.include?(page_data[1][i])
          date = page_data[1][i]          
          tytul = page_data[0][i]
          tytul_oryg = ""
          godzina = page_data[2][i]
          obce_id = page_data[3][i]          
          kino = Kino.find(@@kina_map[:barany])
          reps.concat self.save_rep(obce_id, kino.ID_kino, tytul, tytul_oryg, date, godzina)
      end
      reps
  end     
  
  def self.add_rep_for_sfinks dates
      input_date = dates.kind_of?(Array) ? dates : [dates]
      reps = []
      page_data = self.read_sfinks
#      raise page_data.inspect
#      [ titles, dates, hours, ids]
      for i in 0...page_data[0].length do
          next unless input_date.include?(page_data[1][i])
          date = page_data[1][i]          
          tytul = page_data[0][i]
          tytul_oryg = ""
          godzina = page_data[2][i]
          obce_id = page_data[3][i]          
          kino = Kino.find(@@kina_map[:sfinks])
          reps.concat self.save_rep(obce_id, kino.ID_kino, tytul, tytul_oryg, date, godzina)
      end
      reps
  end 

  def self.add_rep_for_ars dates
      input_date = dates.kind_of?(Array) ? dates : [dates]
      reps = []
      page_data = self.read_ars
#      raise page_data.inspect

      for i in 0...page_data[0].length do
          next unless input_date.include?(page_data[1][i])
          date = page_data[1][i]          
          tytul = page_data[0][i]
          tytul_oryg = ""
          godzina = page_data[2][i]
          obce_id = page_data[3][i]
          kino = case page_data[4][i]
            when /(.*)aneks(.*)/
              Kino.find(@@kina_map[:ars_aneks])
            when /(.*)kiniarnia(.*)/
              Kino.find(@@kina_map[:ars_kiniarnia])
            when /(.*)reduta(.*)/
              Kino.find(@@kina_map[:ars_reduta])
            when /(.*)salon(.*)/
              Kino.find(@@kina_map[:ars_salon])
            when /(.*)sztuka(.*)/
              Kino.find(@@kina_map[:ars_sztuka])
         end
          reps.concat self.save_rep(obce_id, kino.ID_kino, tytul, tytul_oryg, date, godzina)
      end
      reps
  end 
    
  def self.add_rep_for_mikro dates
      input_date = dates.kind_of?(Array) ? dates : [dates]
      reps = []
      for date in input_date
        page_data = self.read_mikro date
#        raise page_data.inspect
        for i in 0...page_data[0].length do
            tytul = page_data[0][i]
            tytul_oryg = page_data[1][i]
            godzina = page_data[2][i]
            obce_id = page_data[3][i]
            kino = Kino.find(@@kina_map[:mikro])
            reps.concat self.save_rep(obce_id, kino.ID_kino, tytul, tytul_oryg, date, godzina)
        end
      end
      reps
  end  

  def self.add_rep_for_kijow dates
      input_date = dates.kind_of?(Array) ? dates : [dates]
      reps = []
      page_data = self.read_kijow 
#        raise page_data.inspect
#    [titles, dates, hours, cine, obce_id]
      for i in 0...page_data[0].length do
          next unless input_date.include?(page_data[1][i])
          tytul = page_data[0][i]
          tytul_oryg = ''
          date = page_data[1][i] 
          obce_id = page_data[4][i]
          godziny = page_data[2][i] + ':00'
          kino = page_data[3][i].include?('studio') ? Kino.find(@@kina_map[:kijow_studio]) : Kino.find(@@kina_map[:kijow])
          reps.concat self.save_rep(obce_id, kino.ID_kino, tytul, tytul_oryg, date, godziny)
      end
      reps
  end  

  def self.check_reps_in_db reps, dates, cine_ids
      input_date = (dates.kind_of?(Array) ? dates : [dates])
      cines = (cine_ids.kind_of?(Array) ? cine_ids : [cine_ids])
      reps_from_db = []
      reps_from_db = Repertuar.find(:all, :conditions => [ "Data IN (?) AND ID_kino IN (?)", input_date, cines])
      ile, removed = 0, 0
      for rep in reps
        ile += 1 if rep.errors.empty? 
      end
      info = []

      info.push("Do bazy dodano poprawnie: <b>#{ile}</b> rekordow")
      info.push("W bazie <b>brakuje #{(reps.length - reps_from_db.length)}</b> rekordow.") if reps_from_db.length < reps.length
      info.push("W bazie <b>jest za duzo o #{(reps_from_db.length - reps.length)}</b> rekordow.")  if reps_from_db.length > reps.length
      for rep_from_db in reps_from_db
        is_in = false
        for rep in reps
          is_in = true if rep.ID_kino == rep_from_db.ID_kino && rep.Data == rep_from_db.Data && rep.Godzina == rep_from_db.Godzina && rep.ID_film == rep_from_db.ID_film
        end
        unless is_in
          removed += 1
          rep_from_db.destroy
#          film = Film.find(rep_from_db.ID_film)
#          info << "<small>#{rep_from_db.kino.nazwa}: <b>#{rep_from_db.Data.to_s}</b> - #{rep_from_db.Godzina.strftime('%H:%M')} \"#{film.tytul}\" - " +
#           "<span id=\"rep_#{rep_from_db.ID_repertuar}\"><a href=\"#\" onclick=\"new Ajax.Updater('rep_" + rep_from_db.ID_repertuar.to_s +  "', '/admin/remove_rep/" + rep_from_db.ID_repertuar.to_s +  "', {asynchronous:true, evalScripts:true}); return false;\">usu�</a></span></small>"
        end
      end
      info.push("Z bazy <b>usunieto #{removed}</b> rekordow.") if removed > 0     

      info
  end
  
  private
  def self.save_rep(obce_id, kino_id, tytul, tytul_oryg, date, godz)
      reps = []
      film_short = FilmShort.find_from_www(obce_id, kino_id, tytul, tytul_oryg)      
      if film_short.nil?    
        logger.debug("### Nie ma w bazie: \"#{tytul}\" (#{tytul_oryg}) ####")
        film_id = nil
      else
        film_id = film_short.id
      end
      godziny = godz.kind_of?(Array) ? godz : [godz]

      for godzina in godziny
        godzina = "0"+godzina if godzina.length == 7
        godzina.gsub!('.', ':')
        rep = Repertuar.new
        rep.ID_film = film_id
        rep.ID_kino = kino_id    
        rep.Data = date
        rep.Godzina = godzina
        begin
          logger.debug("### Debug info - save problem: (rep.inspect) ####") if !rep.save
        rescue
          rep.errors.add_to_base('Duplicated reperturar record')
          logger.debug("### Duplicated reperturar record: (rep.inspect) ####")          
        end
        if film_id.nil?
          error = "Nie ma w bazie: \"#{tytul}\""
          error += " (#{tytul_oryg})" unless tytul_oryg.blank?
          error += "#" + obce_id
          rep.errors.add_to_base(error)
        end
        reps << rep
      end
      reps
  end
  
  validates_presence_of :ID_film, :ID_kino, :Data, :Godzina
   
end
